package com.takeoutOrder.server.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.takeoutOrder.common.constant.OrderConstants;
import com.takeoutOrder.common.constant.UserConstants;
import com.takeoutOrder.common.constant.UserTypeConstants;
import com.takeoutOrder.common.core.domain.entity.SysUser;
import com.takeoutOrder.common.utils.DateUtils;
import com.takeoutOrder.common.utils.uuid.UUID;
import com.takeoutOrder.server.domain.*;
import com.takeoutOrder.server.mapper.AddressBookMapper;
import com.takeoutOrder.server.mapper.OrderDetailMapper;
import com.takeoutOrder.server.mapper.ShoppingCartMapper;
import com.takeoutOrder.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.takeoutOrder.server.mapper.OrdersMapper;
import com.takeoutOrder.server.service.IOrdersService;

import static com.takeoutOrder.common.utils.DateUtils.parseDate;

/**
 * 订单管理Service业务层处理
 *
 * @author linzechen
 * @date 2024-11-27
 */
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询订单管理
     *
     * @param id 订单管理主键
     * @return 订单管理
     */
    @Override
    public Orders selectOrdersById(Long id) {
        return ordersMapper.selectOrdersById(id);
    }

    /**
     * 查询订单管理列表
     *
     * @param orders 订单管理
     * @return 订单管理
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * 新增订单管理
     *
     * @param orders 订单管理
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) {
        String innerCode = UUID.randomUUID().toString();
        orders.setNumber(innerCode);
        orders.setOrderTime(DateUtils.getNowDate());
        /*如果不是待付款,添加下单时间*/
        if (!(orders.getStatus().equals(OrderConstants.ORDER_STATUS_PENDING))) {
            orders.setCheckoutTime(DateUtils.getNowDate());
        }
        /*配送状态为1,代表立即送出,所以不需要送达时间*/
        if (orders.getDeliveryStatus().equals(1)){
            orders.setDeliveryTime(null);
        }
        /*餐具数量让商家自选,这里填个默认值0就可以*/
        if(orders.getTablewareStatus().equals(1)){
            orders.setTablewareNumber(0L);
        }
        /*打包费固定为5元*/
        orders.setPackAmount(5L);
        AddressBook addressBook = addressBookMapper.selectAddressBookById(orders.getAddressBookId());

        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        /*获取订单id*/
        int result = ordersMapper.insertOrders(orders);
        Long orderId = orders.getId();
        /*不论有没有支付,都要添加订单详情*/
        /*先获取用户购物车内的数据,根据用户id*/
        List<ShoppingCart> shoppingCartList=shoppingCartMapper.selectShoppingCartByUserId(orders.getUserId());
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertOrderDetailList(orderDetailList);
        return result;
    }

    /**
     * 修改订单管理
     *
     * @param orders 订单管理
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        Long status = orders.getStatus();
        /*如果是取消订单,则修改取消时间*/
        if (status == 6L) {
            orders.setCancelTime(DateUtils.getNowDate());
        } else if (status == 5L) {
            /*如果是完成订单,则修改完成时间*/
            orders.setDeliveryTime(DateUtils.getNowDate());
        }

        System.out.println("=========================================");
        System.out.println(orders.getDeliveryTime());
        System.out.println(orders.getCancelTime());
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除订单管理
     *
     * @param ids 需要删除的订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByIds(Long[] ids) {
        return ordersMapper.deleteOrdersByIds(ids);
    }

    /**
     * 删除订单管理信息
     *
     * @param id 订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersById(Long id) {
        return ordersMapper.deleteOrdersById(id);
    }

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SaleData selectOrdersSale(Long userId) {
        SaleData saleData = new SaleData();
        /*查询是否为商家,如果不是就不返回订单销量数据*/
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (!sysUser.getDeptId().equals(UserTypeConstants.TYPE_ADMIN)) {
            saleData.setIsAdmin(false);
            return saleData;
        }
        ;

        /*获取套餐销量前五名*/
        List<SetmealData> setmealSales = orderDetailMapper.selectSetmealSale();
        /*获取菜品销量前五名*/
        List<DishData> dishSales = orderDetailMapper.selectDishSale();
        /*获取付款订单数*/
        int finishOrder = ordersMapper.selectSuccessOrders();
        /*获取取消的订单*/
        int cancelOrder = ordersMapper.selectCancleOrders();
        /*退款的订单*/
        int refundOrder = ordersMapper.selectRefundOrders();
        /*订单成功率*/
        Double successRate = (double) finishOrder / (finishOrder + cancelOrder + refundOrder);
        /*付款订单数*/
        saleData.setFinishOrder(finishOrder);
        /*取消订单数*/
        saleData.setCancelOrder(cancelOrder);
        /*退款订单数*/
        saleData.setRefundOrder(refundOrder);
        /*订单成功率*/
        saleData.setSuccessRate(successRate);
        /*套餐售卖前五*/
        saleData.setSetmealData(setmealSales);
        /*菜品售卖前五*/
        saleData.setDishData(dishSales);
        /*设置身份标识为商家/管理员*/
        saleData.setIsAdmin(true);
        return saleData;
    }

    @Override
    public List<DishData> selectDishData() {
        return orderDetailMapper.selectDishSale();
    }
}
